<?php
namespace app\user\controller;

use app\user\controller\Base;
use BitWasp\Bitcoin\Crypto\Random\Random;
use think\Db;
use think\Session;

use BitWasp\Bitcoin\Bitcoin;
use BitWasp\Bitcoin\Key\Factory\HierarchicalKeyFactory;
use BitWasp\Bitcoin\Mnemonic\Bip39\Bip39Mnemonic;
use BitWasp\Bitcoin\Mnemonic\Bip39\Bip39SeedGenerator;
use BitWasp\Bitcoin\Mnemonic\MnemonicFactory;
use Web3p\EthereumUtil\Util;

use xtype\Ethereum\Client as EthereumClient;
use xtype\Ethereum\Utils;
use kornrunner\Keccak;
use Lib\Tool;

use EthereumRPC\EthereumRPC;
use ERC20\ERC20;

class Assets extends Base
{
    public function Recharge(){
        if (IsPost()){
            $Data = Param();
            if ($Data['num'] == '' || $Data['num'] <= 0 || !is_numeric($Data['num'])){
                return ['status'=>0,'message'=>'金额错误'];
            }
//            if ($Data['hash'] == ''){
//                return ['status'=>0,'message'=>'请上传凭证'];
//            }
            $add['user_id'] = $this->user_id;
            $add['num'] = $Data['num'];
            $add['hash'] = $Data['hash'];
            $add['add_time'] = time();
            if (Db::name('user_recharge')->insert($add)){
                return ['status'=>1,'message'=>'提交成功'];
            }else{
                return ['status'=>0,'message'=>'提交失败'];
            }
        }
        $this->assign('Config',Config());
        return $this->fetch('Recharge');
    }

    /**
     * 小金库
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function Index(){
        //会员信息
        $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
        $this->assign('UserInfo',$UserInfo);

        $Config = Db::name('system_config')->where('id=1')->find();
        $this->assign('Config',$Config);

//        //轮播公告
//        $Notice = Db::name('notice')->where(['lang'=>1])->order('id desc')->limit(3)->select();
//        $this->assign('Notice',$Notice);


//        //提币记录
//        $WithdrawList = Db::name('user_withdraw')->where(['user_id'=>$UserInfo['id']])->order('add_time desc')->limit(5)->select();
//        $this->assign('WithdrawList',$WithdrawList);

//        //邀请挖矿
//        $url = 'http://'.$_SERVER['HTTP_HOST'];
//        $this->assign('url',$url);
        //查看会员是否理财
        $Check = Db::name('user_money')->where(['user_id'=>$UserInfo['id'],'status'=>['in',[1,2]]])->find();
        if ($Check){
            $is_money = 1;
        }else{
            $is_money = 0;
        }
        $this->assign('is_money',$is_money);

        return $this->fetch('Index');
    }

    public function downloadImage()
    {
        $url = Param('img');
        $filename = $_SERVER['DOCUMENT_ROOT'].$url;
        $arr = explode('/',$filename);
        $name = $arr[count($arr) - 1];
        $filename = "1.jpg";//图片地址,可以绝对地址也可以相对地址
        header("Content-Type: application/force-download");
        header('Content-Disposition: attachment; filename="'.$name.'"');
        $img = file_get_contents($filename);
        echo $img;
        die;
        $path='images/';
        $url = $_SERVER['HTTP_HOST'].$url;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        $file = curl_exec($ch);
        curl_close($ch);
        $this->saveAsImage($url, $file, $path);
    }

    private function saveAsImage($url, $file, $path)
    {
        $filename = pathinfo($url, PATHINFO_BASENAME);
        $resource = fopen($path . $filename, 'a');
        fwrite($resource, $file);
        fclose($resource);
    }

    public function CreateDBS(){
        if (IsPost()){
            $Data = Param();
            $check = UserWalletInfo(['username'=>$Data['username']]);
            if ($check){
                return ['status'=>0,'message'=>'用户名已存在'];
            }

            $user_id = Session::get('user_id');
            $address = createAddress($user_id);
            $privkey = createPrivkey($address);
            $bip39 = createBip39();
            $Insert['user_id'] = $user_id;
            $Insert['username'] = $Data['username'];
            $Insert['password_login'] = md5($Data['password']);
            $Insert['address'] = $address;
            $Insert['privkey'] = $privkey;
            $Insert['bip39'] = $bip39;
//            $Insert['is_master'] = 0;  //不是主地址
            $Insert['status'] = 0; //未激活
            $Insert['time'] = time();
            $address_id = Db::name('user_wallet_address')->insertGetId($Insert);
            //地址列表
            $list['user_id'] = $user_id;
            $list['address_id'] = $address_id;
            $list['is_master'] = 0; //次钱包
            $list['time'] = time();
            $res = Db::name('user_address_list')->insert($list);
            if ($res && $address_id){
                return ['status'=>1,'message'=>'创建成功'];
            }else{
                return ['status'=>0,'message'=>'创建失败'];
            }
        }
    }

    /**
     * 充币
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function AssetsRecharge(){

        //系统参数
        $Config = Config();
        $this->assign('Config',$Config);

//        $User = Db::name('user')->where(['id'=>Session::get('user_id')])->find();
//        if ($User['trx_address'] == ''){
//            //生成波场地址
//            $Trx = CreateTrxAddress();
//            Db::name('user')->where(['id'=>$User['id']])->update($Trx);
//            $address = $Trx['trx_address'];
//        }else{
//            $address = $User['trx_address'];
//        }
//        $this->assign('user',$User);
//
//        $this->assign('address',$address);
        $this->assign('address','TFb7JWRjedbiqxL9Q1tcgpsi1RS22y1A8Y');
        return $this->fetch('AssetsRecharge');
    }



    /**
     * 提币
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function AssetsWithdraw(){

        //会员信息
        $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
        $this->assign('UserInfo',$UserInfo);

        //系统参数
        $Config = Config();
        $this->assign('Config', $Config);

        //Post请求
        if (IsPost()) {
            //提现开关

            //请求数据
            $Data = Param();

            if ($Config['withdraw_toggle'] == 0){
                return ['status' => 0, 'message' => '提现通道暂未开放'];
            }

//            $start = strtotime(date('Y-m-d '.$Config['withdraw_begin']));
//            $end = strtotime(date('Y-m-d '.$Config['withdraw_end']));
//            if (time()<$start || time()>$end){
//                return ['status' => 0, 'message' => '提币时间在每天'.$Config['withdraw_begin'].'至'.$Config['withdraw_end']];
//            }

            $BeginTime = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
            $EndTime = date("Y-m-d H:i:s", mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1);

            $Where['add_time'] = array(array('egt', $BeginTime), array('elt', $EndTime));
            $Where['user_id'] = $UserInfo['id'];
            $Count = Db::name('user_withdraw')->where($Where)->count();

            //判断当日提现次数
            if ($Count >= $Config['withdraw_count']) {
                return ['status' => 0, 'message' => '温馨提示：每天只能提币'.$Config['withdraw_count'].'次。'];
            }

            $Check = Db::name('user_withdraw')->where(['user_id'=>$UserInfo['id']])->order('id desc')->find();
            if ($Check){
                if ((time() - $Check['add_time']) < 5*60){
                    return ['status' => 0, 'message' => '提币过于频繁，请5分钟后再试'];
                }
            }
            if ($Data['num'] == '' || $Data['num'] <= 0 || !is_numeric($Data['num'])){
                return ['status'=>0,'message'=>'请填写数量'];
            }
//            if ($Data['bank_user'] == '' || $Data['bank_name'] == '' || $Data['bank_num'] == '' || $Data['bank_open'] == ''){
//                return ['status'=>0,'message'=>'银行信息填写错误'];
//            }
            if ($Data['address'] == ''){
                return ['status'=>0,'message'=>'请输入提币地址'];
            }
            if ($Data['num'] < $Config['withdraw_min1']){
                return ['status'=>0,'message'=>'单次最低提现'.$Config['withdraw_min1']];
            }
            if ($Data['num'] > $Config['withdraw_max1']){
                return ['status'=>0,'message'=>'单次最大提现'.$Config['withdraw_max1']];
            }
            //判断余额是否足够
            if ($Data['num'] > $UserInfo['balance_1']) {
                return ['status' => 0, 'message' => 'USDT余额不足'];
            }
//            //提现整数倍
//            if (($Data['num'] % $Config['withdraw_down']) != 0) {
//                return ['status' => 0, 'message' => '提现数量须为' . $Config['withdraw_multiple'] . '的整数倍'];
//            }

            //判断支付密码是否正确
//            if(md5($Data['pass_pay']) != $UserInfo['password_pay']){
//                return ['status'=>0,'message'=>'支付密码错误'];
//            }
            if(md5($Data['password']) != $UserInfo['password_login']){
                return ['status'=>0,'message'=>'密码错误'];
            }
            //验证码验证
//            if($UserInfo['reg_type'] == 1){  //手机验证码
//                $Phone = $UserInfo['mobile_prefix'].$UserInfo['phone'];
//                $CodeRes = checkCode($Phone,$Data['code'],1);
//            }else{
//                $CodeRes = checkCode($UserInfo['email'],$Data['code'],2);
//            }
//            if($CodeRes['status'] != 1){
//                return $CodeRes;
//            }
            Db::startTrans();
            $UserSave = [];

            $UserSave['balance_1'] = $UserInfo['balance_1'] - $Data['num']; //更新余额
            $res[] = Db::name('user')->where(['id'=>$UserInfo['id']])->update($UserSave);
            //提币到外部
            $fee = $Data['num']*$Config['withdraw_fees']/100;
            $real_num = $Data['num'] - $fee;
            $AddData = [
                'user_id' => $UserInfo['id'],   //会员ID
//                'address' => $Data['address'],  //提币地址
                'type' => 1,  //提币币种
                'num' => $Data['num'],  //提币数量
                'fees' => $fee, //手续费
                'real_num' => $real_num, //实际到账数量
                'bank_name'=>$Data['bank_name'],
                'bank_user'=>$Data['bank_user'],
                'bank_num'=>$Data['bank_num'],
                'bank_open'=>$Data['bank_open'],
                'add_time' => time(),   //添加时间
            ];
            $id = Db::name('user_withdraw')->insertGetId($AddData);
            $res[] = FinanceAdd($UserInfo['id'],$UserInfo['id'],$Data['num'],1,4,'提现','','',$id);
            //更新数据库
            if (check_res($res)) {
                Db::commit();
                return ['status' => 1, 'message' => '提交成功'];
            } else {
                Db::rollback();
                return ['status' => 0, 'message' => '系统错误，请重试'];
            }
        }

        return $this->fetch('Withdraw');
    }


    /**
     * 转账
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function AssetsTransfer(){
        //会员信息
        $UserInfo = UserInfo(['id'=>$this->user_id]);
        $this->assign('UserInfo',$UserInfo);

        //系统参数
        $Config = Config();
        $this->assign('Config', $Config);

        //Post请求
        if (IsPost()) {
            //请求数据
            $Data = Param();
            if ($Data['num'] == '' || $Data['num'] <= 0 || !is_numeric($Data['num'])){
                return ['status' => 0, 'message' => '请填写金额'];
            }
            if ($Data['to_user'] == ''){
                return ['status' => 0, 'message' => '请输入转出用户'];
            }
            $ToUser = UserInfo(['username'=>$Data['to_user']]);
            if (!$ToUser){
                return ['status' => 0, 'message' => '转出用户不存在'];
            }
            $UserInfo = UserInfo(['id'=>$this->user_id]);
            if ($UserInfo['balance_1'] < $Data['num']){
                return ['status' => 0, 'message' => '余额不足'];
            }
            if (md5($Data['password']) != $UserInfo['password_login']){
                return ['status' => 0, 'message' => '密码错误'];
            }
            Db::startTrans();
            $res[] = Db::name('user')->where(['id'=>$UserInfo['id']])->setDec('balance_1',$Data['num']);
            $res[] = Db::name('user')->where(['id'=>$ToUser['id']])->setInc('balance_1',$Data['num']);
            $res[] = FinanceAdd($UserInfo['id'],$ToUser['id'],$Data['num'],1,5,'转出');
            $res[] = FinanceAdd($ToUser['id'],$UserInfo['id'],$Data['num'],1,5,'转入');
            if (check_res($res)){
                Db::commit();
                return ['status' => 1, 'message' => '转出成功'];
            }else{
                Db::rollback();
                return ['status' => 0, 'message' => '转出失败'];
            }
        }

        return $this->fetch('AssetsTransfer');
    }

    /**
     * 币币转换
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function AssetsChange(){
        //会员信息
        $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
        $this->assign('UserInfo',$UserInfo);

        $Config = Db::name('system_config')->where('id=1')->find();
        $this->assign('Config',$Config);

        //Post请求
        if (IsPost()) {
            //请求数据
            $Data = Param();

            //判断支付密码是否正确
            if(md5($Data['pass_pay']) != $UserInfo['password_pay']){
                return ['status'=>0,'message'=>'支付密码错误'];
            }

            define('ACCOUNT_ID', '97654126'); // your account ID
            define('ACCESS_KEY','47bafbe5-1qdmpe4rty-b8a90c09-157a1'); // your ACCESS_KEY
            define('SECRET_KEY', '0ece64cc-238f7e3d-a8417299-599ab'); // your SECRET_KEY

            //实例化类库
            $req = new Lib();
            // 获取account-id, 用来替换ACCOUNT_ID
            $Rate = [];
            $Rate['btc']= (array)$req->get_detail_merged('btcusdt')->tick;
            $Btc_Usdt = $Rate['btc']['close'];   //BTC转USDT汇率
            $Usdt_Btc = 1 / $Btc_Usdt;   //USDT转BTC汇率
            $Usdt_Mcg = $Config['usdt_mcg'];

            //根据转账类型判断余额
            if ($Data['type'] == 1 && $Data['to_type'] == 2) {   //USDT转BTC
                if ($Data['num'] > $UserInfo['balance_1']) {
                    return ['status' => 0, 'message' => "USDT余额不足，当前USDT" . $UserInfo['balance_1']];
                } else {
                    $UserSave['balance_1'] = $UserInfo['balance_1'] - $Data['num'];
                    $UserSave['balance_2'] = $UserInfo['balance_2'] + $Data['num'] * $Usdt_Btc;
                }
                $AddData['rate'] = $Usdt_Btc;
                $AddData['to_num'] = $Data['num'] * $Usdt_Btc;
            }

            if ($Data['type'] == 1 && $Data['to_type'] == 3) {   //USDT转MCG
                if ($Data['num'] > $UserInfo['balance_1']) {
                    return ['status' => 0, 'message' => "USDT余额不足，当前USDT" . $UserInfo['balance_1']];
                } else {
                    $UserSave['balance_1'] = $UserInfo['balance_1'] - $Data['num'];
                    $UserSave['balance_3'] = $UserInfo['balance_3'] + $Data['num'] * $Usdt_Mcg;
                }
                $AddData['rate'] = $Usdt_Mcg;
                $AddData['to_num'] = $Data['num'] * $Usdt_Mcg;
            }

            if ($Data['type'] == 2 && $Data['to_type'] == 1) {   //BTC转USDT
                if ($Data['num'] > $UserInfo['balance_2']) {
                    return ['status' => 0, 'message' => "BTC余额不足，当前BTC" . $UserInfo['balance_1']];
                } else {
                    $UserSave['balance_2'] = $UserInfo['balance_2'] - $Data['num'];
                    $UserSave['balance_1'] = $UserInfo['balance_1'] + $Data['num'] * $Btc_Usdt;
                }
                $AddData['rate'] = $Btc_Usdt;
                $AddData['to_num'] = $Data['num'] * $Btc_Usdt;
            }

            $AddData['user_id'] = $UserInfo['id'];
            $AddData['from'] = $Data['type'];
            $AddData['to'] = $Data['to_type'];
            $AddData['num'] = $Data['num'];
            $AddData['add_time'] = time();

            if(Db::name('user')->where(['id'=>$UserInfo['id']])->update($UserSave)){
                Db::name('user_change')->insert($AddData);
                FinanceAdd($UserInfo['id'], $UserInfo['id'], $Data['num'], $Data['type'], 11, '转换扣除');
                FinanceAdd($UserInfo['id'], $UserInfo['id'], $AddData['to_num'], $Data['to_type'], 12, '转换获得');
            }
            return ['status' => 1, 'message' => '转换成功'];
        }

        return $this->fetch('AssetsChange');
    }

    public function forUpload()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('image');

        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->validate(['size'=>1567800000,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads/assets');

        if($info){
            //返回上传图片路径
            $path = "/uploads/assets/".$info->getSaveName();
            return ['status'=>1,'message'=>$path];
        }else{
            // 上传失败获取错误信息
            return ['status'=>0,'message'=>$file->getError()];
        }
    }
}